package ink.sunflowerk.utils;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;

/**
 * @author zhaokuii11@163.com
 * @create 2021-12-01 20:59
 * @Description 判断请求类型、ajax还是 普通的
 */
public class CrowdUtil {
    /**
     * 判断当前请求是 ajax还是 普通请求
     * 判断依据：
     * Accept : application/json; charset=utf-8
     * X-requested-with: XMLHttpRequest
     * 只要有一个就可以
     *
     * @param request 请求对象
     * @return Boolean true ajax请求、false 普通请求
     */
    public static boolean judgeRequestType(HttpServletRequest request) {
        //1. 获取请求消息头
        String accept = request.getHeader("Accept");
        String xRequestedwith = request.getHeader("X-requested-with");
        //2. 判断
        if (accept != null && accept.contains("application/json") ||
                xRequestedwith != null && xRequestedwith.contains("XMLHttpRequest")) {
            return true;
        }
        return false;
    }

    /**
     * MD5加码 生成32位md5码
     *
     * @param source 传入的明文字符串
     * @return 加密结果
     */
    public static String str2MD5(String source) {
        if (source == null || "".equals(source))
            return "";
        
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
//            log.info(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = source.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }
}